import React, { createContext, useContext, useState, ReactNode, useEffect } from 'react';
import './GlobalLoading.css';

// 创建一个独立的全局loading管理器
export class GlobalLoadingManager {
    private static instance: GlobalLoadingManager;
    private loadingCount: number = 0;
    private callbacks: Array<(isLoading: boolean) => void> = [];

    private constructor() {}

    public static getInstance(): GlobalLoadingManager {
        if (!GlobalLoadingManager.instance) {
            GlobalLoadingManager.instance = new GlobalLoadingManager();
        }
        return GlobalLoadingManager.instance;
    }

    public showLoading(): void {
        this.loadingCount++;
        this.notifyCallbacks(true);
    }

    public hideLoading(): void {
        this.loadingCount = Math.max(0, this.loadingCount - 1);
        if (this.loadingCount === 0) {
            this.notifyCallbacks(false);
        }
    }

    public addCallback(callback: (isLoading: boolean) => void): void {
        this.callbacks.push(callback);
    }

    public removeCallback(callback: (isLoading: boolean) => void): void {
        this.callbacks = this.callbacks.filter((cb) => cb !== callback);
    }

    private notifyCallbacks(isLoading: boolean): void {
        this.callbacks.forEach((callback) => callback(isLoading));
    }
}

// 导出供api拦截器和其他非React环境使用的方法
export const globalLoading = {
    show: () => GlobalLoadingManager.getInstance().showLoading(),
    hide: () => GlobalLoadingManager.getInstance().hideLoading(),
};

// Provider组件，用于管理全局loading状态
export const GlobalLoadingProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
    const [isLoading, setIsLoading] = useState<boolean>(false);
    const manager = GlobalLoadingManager.getInstance();

    useEffect(() => {
        // 注册回调来更新React状态
        const callback = (loading: boolean) => {
            setIsLoading(loading);
        };

        manager.addCallback(callback);

        // 清理函数
        return () => {
            manager.removeCallback(callback);
        };
    }, [manager]);

    return (
        <>
            {children}
            {isLoading && <GlobalLoadingOverlay />}
        </>
    );
};

// 蒙层组件，显示loading动画和文字
export const GlobalLoadingOverlay: React.FC = () => {
    return (
        <div className="global-loading-overlay">
            <div className="global-loading-content">
                <div className="global-loading-spinner"></div>
                <div className="global-loading-text">加载中...</div>
            </div>
        </div>
    );
};

// 默认导出Provider组件
export default GlobalLoadingProvider;
